package com.baizhi.controller;


import com.baizhi.entity.LayuiUser;
import com.baizhi.service.LayuiUserRoleService;
import com.baizhi.service.LayuiUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhengg
 * @since 2020-07-30
 */
@RestController
@RequestMapping("/layui-user")
public class LayuiUserController {
    @Autowired
    private LayuiUserService us;
    @RequestMapping("/login")
    public Map<String,Object> login(String username, String password){
        //使用shiro做登录操作
        Subject subject = SecurityUtils.getSubject();//封装shiro正确的用户名和密码
        //拿用户输入的账号和密码跟正确的账号和密码进行比对。
        try{
            //认证成功没有异常信息，认证失败会抛异常信息
            subject.login(new UsernamePasswordToken(username,password));
        }catch (Exception e){
            e.printStackTrace();//在控制台上打印
            Map<String,Object> map=new HashMap<>();
            map.put("code",1);
            map.put("msg",e.getMessage());
            return map;
        }

        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        return map;
    }

    @RequestMapping("/logout")
    public void logout(){
        //登出清除缓存
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

    }

    @RequestMapping("selectAll")
    public Map<String,Object> selectAll(){
        List<LayuiUser> userList = us.list();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("data",userList);
        return map;
    }

    @RequestMapping("/add")
    public Map<String,Object> add(LayuiUser user){
        us.save(user);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        return map;
    }
    @Autowired
    private LayuiUserRoleService urs;
    @RequestMapping("/grantRole")
    public Map<String,Object> grantRole(Integer[] roleIds,Integer userId) throws JSONException {
        for(Integer id:roleIds){
            System.out.println(id);
        }
        System.out.println(userId);
//        for(Integer roleId:roleIds){
//            LayuiUserRole lur=new LayuiUserRole(userId,roleId);
//            urs.save(lur);
//        }
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        return map;
    }
}
